const {
  OK,
  Bad_Request,
  Internal_Server_Error,
} = require('@constant/http.status');

class Tools {
  generateBody = ({ code, message, status, result = {} }) => {
    return {
      code,
      message,
      status,
      result,
    };
  };
  generateBodySuccess = (result) => {
    return this.generateBody({
      code: '0',
      message: 'ok',
      status: OK,
      result,
    });
  };
  paramsError = (message) => {
    return this.generateBody({
      code: '0001',
      message,
      status: Bad_Request,
    });
  };
  serverErr = (code, message) => {
    return this.generateBody({
      code,
      message,
      status: Internal_Server_Error,
    });
  };
  validIncorrectParameter = (schema, ctx, dataType = 'body') => {
    const { error, value } = schema.validate(ctx.request[dataType], {
      context: ctx,
      abortEarly: false,
    });

    if (error || !value) {
      const message = error ? error.details[0].message : '参数不能为空';

      return ctx.app.emit('error', this.paramsError(message), ctx);
    }
    return null;
  };
  getPagination = (page_num = 1, page_size = 10) => {
    const offset = (page_num - 1) * page_size;

    const limit = +page_size;

    return {
      offset,
      limit,
    };
  };
  controller = async (params, service) => {
    return await service(params);
  };
  emit = (ctx, res, success, error) => {
    return res
      ? ctx.app.emit('success', success, ctx)
      : ctx.app.emit('error', error, ctx);
  };
}

module.exports = new Tools();
